package com.yhyvr.service.imp;


import com.lz.kit.LogKit;
import com.lz.mybatis.jdbc.auto.dao.PhoneCodeMapper;
import com.lz.mybatis.jdbc.auto.model.PhoneCode;
import com.lz.mybatis.jdbc.auto.model.PhoneCodeExample;
import com.lz.tool.RandomTool;
import com.lz.tool.UUIDTool;
import com.yhyvr.service.SmsService;
import org.springframework.stereotype.Service;
import com.yhyvr.sms.SendTemplateSMS;
import com.yhyvr.sms.exception.SmsRunTimeException;

import javax.annotation.Resource;
import java.util.Date;

@Service("SmsServiceImp")
public class SmsServiceImp implements SmsService {

	@Resource
	private SendTemplateSMS sendTemplateSMS;

	@Resource
	private PhoneCodeMapper phoneCodeService;
	/**
	 * 获取验证码
	 * @param phoneNumber
	 * @return
	 */
	@Override
	public String getValidateCode(String phoneNumber){
		String number="";
		try{
			number = RandomTool.getCode(4, RandomTool.TYPE0);
		 sendTemplateSMS.sendSms(phoneNumber,number);
		Date createTime=new Date();
		PhoneCode phone_code=new PhoneCode();
		phone_code.setId(UUIDTool.getUUID());
		phone_code.setCode(number);
		phone_code.setPhone(phoneNumber);
		phone_code.setCreateTime(createTime);
		phone_code.setExpiresTime(new Date(createTime.getTime()+10*60000));
		phoneCodeService.insertSelective(phone_code);
			return number;
		}catch(SmsRunTimeException e){
			LogKit.error(e.getMessage(),e);
			throw new SmsRunTimeException("-1",e.getMessage());
		}
		
	}
	
	/**
	 * 验证验证码是否可用
	 */
	@Override
	public boolean validateCode(String phoneNumber, String code) {
		PhoneCodeExample phoneCodeExample = new PhoneCodeExample();
		phoneCodeExample.createCriteria().andPhoneEqualTo(phoneNumber).andCodeEqualTo(code).andExpiresTimeGreaterThan(new Date());
		return phoneCodeService.countByExample(phoneCodeExample)>0;
	}
	
	
}
